package com.qf.user.service.impl;

import com.qf.user.dao.UserDao;
import com.qf.user.exception.PasswordIncorrectException;
import com.qf.user.exception.UnkownUsernameException;
import com.qf.user.model.TbUser;
import com.qf.user.service.UserService;
import com.qf.user.utils.MD5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

//service层，业务逻辑层
@Component //交给spring管理
public class UserServiceImpl implements UserService {
    @Autowired //该注解在变量上表示根据类型完成自动装配
    // 如果在方法上表示如果方法有参数就去spring容器中自动查找参数
    private UserDao userdao;
    //登录的逻辑判断
    @Override
    public TbUser login(String username, String password) throws Exception {
        //先验证用户名是否为空或者不存在
        if ("".equals(username) || username==null){
            throw new UnkownUsernameException();
        }
        //校验用户名或密码是否正确
        TbUser user = userdao.findUserByUsername(username);
        if (user==null){
            throw new UnkownUsernameException();
        }
        //将用户传入的密码进行加密
        String md5 = MD5Utils.md5(password, user.getSalt());
        //校验密码是否正确
        if (!user.getPassword().equals(md5)){
            throw new PasswordIncorrectException();
        }
        return user;
    }
}
